<template>
    <!-- 页面整体布局 -->
    <div class="book-page">
        <!-- 卡片容器 -->
        <el-card class="book-card">
            <!-- 标题 -->
            <h2 class="book-title">新增书本申请</h2>
            <!-- 书本申请表单 -->
            <el-form :model="form" label-width="140px" class="book-form">
                <!-- 基础信息两栏布局 -->
                <el-row :gutter="40">
                    <!-- 左栏：角色信息和封面 -->
                    <el-col :span="10">
                        <!-- 角色名称（自动填充，禁止编辑） -->
                        <el-form-item label="角色名称">
                            <el-input
                                v-model="form.name"
                                :readonly="true"
                                disabled
                                placeholder="自动填充为当前登录人姓名"
                            />
                        </el-form-item>
                        <!-- 角色简介 -->
                        <el-form-item label="简介">
                            <el-input
                                v-model="form.desc"
                                type="textarea"
                                rows="4"
                                placeholder="请输入简介"
                            />
                        </el-form-item>
                        <!-- 是否显示头像 -->
                        <el-form-item label="是否显示头像">
                            <el-switch v-model="form.isAvatar" />
                        </el-form-item>
                        <!-- 头像链接及预览 -->
                        <el-form-item label="头像链接">
                            <el-input
                                v-model="form.avatar"
                                placeholder="请输入头像图片链接"
                            />
                            <el-image
                                v-if="form.avatar"
                                :src="form.avatar"
                                style="
                                    width: 4rem;
                                    height: 6rem;
                                    margin-top: 8px;
                                "
                                fit="contain"
                                :preview-src-list="[form.avatar]"
                                preview-teleported
                            />
                        </el-form-item>
                        <!-- 书本封面正面及预览 -->
                        <el-form-item label="书本封面正面">
                            <el-input
                                v-model="form.bookfront1"
                                placeholder="书本封面正面图片链接"
                            />
                            <el-image
                                v-if="form.bookfront1"
                                :src="form.bookfront1"
                                style="
                                    width: 4rem;
                                    height: 6rem;
                                    margin-top: 8px;
                                "
                                fit="contain"
                                :preview-src-list="[form.bookfront1]"
                                preview-teleported
                            />
                        </el-form-item>
                        <!-- 书本封面背面及预览 -->
                        <el-form-item label="书本封面背面">
                            <el-input
                                v-model="form.bookfront2"
                                placeholder="书本封面背面图片链接"
                            />
                            <el-image
                                v-if="form.bookfront2"
                                :src="form.bookfront2"
                                style="
                                    width: 4rem;
                                    height: 6rem;
                                    margin-top: 8px;
                                "
                                fit="contain"
                                :preview-src-list="[form.bookfront2]"
                                preview-teleported
                            />
                        </el-form-item>
                    </el-col>
                    <!-- 右栏：内容页和封底 -->
                    <el-col :span="12">
                        <!-- 内容页正面背景图及预览 -->
                        <el-form-item label="内容页正面背景图">
                            <el-input
                                v-model="form.bookPage1"
                                placeholder="图片链接"
                            />
                            <el-image
                                v-if="form.bookPage1"
                                :src="form.bookPage1"
                                style="
                                    width: 4rem;
                                    height: 6rem;
                                    margin-top: 8px;
                                "
                                fit="contain"
                                :preview-src-list="[form.bookPage1]"
                                preview-teleported
                            />
                        </el-form-item>
                        <!-- 内容页背面背景图及预览 -->
                        <el-form-item label="内容页背面背景图">
                            <el-input
                                v-model="form.bookPage2"
                                placeholder="图片链接"
                            />
                            <el-image
                                v-if="form.bookPage2"
                                :src="form.bookPage2"
                                style="
                                    width: 4rem;
                                    height: 6rem;
                                    margin-top: 8px;
                                "
                                fit="contain"
                                :preview-src-list="[form.bookPage2]"
                                preview-teleported
                            />
                        </el-form-item>
                        <!-- 书本封底及预览 -->
                        <el-form-item label="书本封底">
                            <el-input
                                v-model="form.bookBack"
                                placeholder="图片链接"
                            />
                            <el-image
                                v-if="form.bookBack"
                                :src="form.bookBack"
                                style="
                                    width: 4rem;
                                    height: 6rem;
                                    margin-top: 8px;
                                "
                                fit="contain"
                                :preview-src-list="[form.bookBack]"
                                preview-teleported
                            />
                        </el-form-item>
                        <el-form-item>
                            <h1>页组使用教程</h1>
                            <el-image
                                src="https://s3plus.meituan.net/opapisdk/op_ticket_1_885190757_1761851162301_qdqqd_1f1q81.png"
                                style="width: 20rem; margin-top: 8px"
                                fit="contain"
                                :preview-src-list="[
                                    `https://s3plus.meituan.net/opapisdk/op_ticket_1_885190757_1761851162301_qdqqd_1f1q81.png`,
                                    `https://zkaicc.huilan.com/aicc/api/aicc-file/miniofile/preViewPicture/aicc/qdqqd_1761851209348.png`,
                                    `https://s3plus.meituan.net/opapisdk/op_ticket_1_885190757_1761851215826_qdqqd_v8woih.png`,
                                ]"
                                preview-teleported
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- essay 动态表单：书本内容页组 -->
                <el-form-item label="书本内容" class="essay-form-item">
                    <!-- 每个页组 -->
                    <div
                        v-for="(page, pageIdx) in form.essay"
                        :key="pageIdx"
                        class="essay-page-block"
                    >
                        <el-divider>第{{ pageIdx + 1 }}组页</el-divider>
                        <!-- 页码输入（自动生成） -->
                        <el-row :gutter="24">
                            <el-col :span="12">
                                <el-form-item label="页码">
                                    <el-input
                                        v-model="page.PagesNumeStr"
                                        style="width: 400px"
                                        placeholder="如 1,2"
                                        @change="
                                            (val) =>
                                                handlePagesNumeChange(page, val)
                                        "
                                    />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="24">
                            <!-- 正面内容 -->
                            <el-col :span="12">
                                <div class="essay-content-title">正面内容</div>
                                <!-- 每个内容项 -->
                                <div
                                    v-for="(item, idx) in page.frontContent"
                                    :key="idx"
                                    class="essay-content-row"
                                >
                                    <!-- 类型选择 -->
                                    <el-select
                                        v-model="item.type"
                                        placeholder="类型"
                                        style="width: 180px"
                                    >
                                        <el-option label="文本" value="text" />
                                        <el-option label="图片" value="img" />
                                        <el-option label="图片2" value="img2" />
                                        <el-option label="图片3" value="img3" />
                                    </el-select>
                                    <!-- 文本内容输入 -->
                                    <template v-if="item.type === 'text'">
                                        <el-input
                                            v-model="item.text"
                                            type="textarea"
                                            placeholder="文本内容"
                                            style="width: 400px"
                                        />
                                    </template>
                                    <!-- 图片内容输入及预览 -->
                                    <template v-else>
                                        <el-input
                                            v-model="item.Image"
                                            placeholder="图片链接"
                                            style="width: 400px"
                                        />
                                        <el-image
                                            v-if="item.Image"
                                            :src="item.Image"
                                            style="
                                                width: 4rem;
                                                height: 6rem;
                                                margin-top: 8px;
                                            "
                                            fit="contain"
                                            :preview-src-list="[item.Image]"
                                            preview-teleported
                                        />
                                    </template>
                                    <!-- 删除内容按钮 -->
                                    <el-button
                                        icon="el-icon-delete"
                                        type="danger"
                                        size="small"
                                        @click="
                                            removeEssayContent(
                                                page.frontContent,
                                                idx
                                            )
                                        "
                                        circle
                                    />
                                </div>
                                <!-- 添加内容按钮 -->
                                <el-button
                                    size="small"
                                    type="primary"
                                    @click="addEssayContent(page.frontContent)"
                                    :disabled="
                                        isEssayContentDisabled(
                                            page.frontContent
                                        )
                                    "
                                    style="margin-top: 8px"
                                    >添加内容</el-button
                                >
                            </el-col>
                            <!-- 背面内容 -->
                            <el-col :span="12">
                                <div class="essay-content-title">背面内容</div>
                                <div
                                    v-for="(item, idx) in page.backContent"
                                    :key="idx"
                                    class="essay-content-row"
                                >
                                    <el-select
                                        v-model="item.type"
                                        placeholder="类型"
                                        style="width: 180px"
                                    >
                                        <el-option label="文本" value="text" />
                                        <el-option label="图片" value="img" />
                                        <el-option label="图片2" value="img2" />
                                        <el-option label="图片3" value="img3" />
                                    </el-select>
                                    <template v-if="item.type === 'text'">
                                        <el-input
                                            v-model="item.text"
                                            type="textarea"
                                            placeholder="文本内容"
                                            style="width: 400px"
                                        />
                                    </template>
                                    <template v-else>
                                        <el-input
                                            v-model="item.Image"
                                            placeholder="图片链接"
                                            style="width: 400px"
                                        />
                                        <el-image
                                            v-if="item.Image"
                                            :src="item.Image"
                                            style="
                                                width: 4rem;
                                                height: 6rem;
                                                margin-top: 8px;
                                            "
                                            fit="contain"
                                            :preview-src-list="[item.Image]"
                                            preview-teleported
                                        />
                                    </template>
                                    <el-button
                                        icon="el-icon-delete"
                                        type="danger"
                                        size="small"
                                        @click="
                                            removeEssayContent(
                                                page.backContent,
                                                idx
                                            )
                                        "
                                        circle
                                    />
                                </div>
                                <el-button
                                    size="small"
                                    type="primary"
                                    @click="addEssayContent(page.backContent)"
                                    :disabled="
                                        isEssayContentDisabled(page.backContent)
                                    "
                                    style="margin-top: 8px"
                                    >添加内容</el-button
                                >
                            </el-col>
                        </el-row>
                        <!-- 删除页组按钮 -->
                        <el-row>
                            <el-col :span="24">
                                <el-button
                                    size="small"
                                    type="danger"
                                    @click="removeEssayPage(pageIdx)"
                                    style="margin-top: 12px"
                                    >删除本组页</el-button
                                >
                            </el-col>
                        </el-row>
                    </div>
                    <!-- 添加页组按钮 -->
                    <el-button
                        size="large"
                        type="success"
                        @click="addEssayPage"
                        style="margin-top: 18px"
                        >添加页组</el-button
                    >
                </el-form-item>
                <!-- 提交按钮 -->
                <el-form-item>
                    <el-button
                        type="primary"
                        :loading="loading"
                        @click="handleSubmit"
                        round
                        style="width: 220px; font-size: 1.2rem"
                        >提交申请</el-button
                    >
                </el-form-item>
            </el-form>
            <!-- 分割线 -->
            <el-divider />
            <!-- 书本申请记录表格 -->
            <h2
                class="book-title"
                style="text-align: left; margin-bottom: 16px"
            >
                我的书本申请记录
            </h2>
            <el-table :data="pagedBooks" class="book-table">
                <!-- 各字段展示，带图片预览 -->
                <el-table-column prop="name" label="名称" width="120" />
                <el-table-column prop="avatar" label="头像" width="100">
                    <template #default="scope">
                        <el-image
                            v-if="scope.row.avatar"
                            :src="scope.row.avatar"
                            style="width: 3rem; height: 3rem"
                            fit="contain"
                            :preview-src-list="[scope.row.avatar]"
                            preview-teleported
                        />
                    </template>
                </el-table-column>
                <el-table-column
                    prop="bookfront1"
                    label="书本封面正面"
                    width="100"
                >
                    <template #default="scope">
                        <el-image
                            v-if="scope.row.bookfront1"
                            :src="scope.row.bookfront1"
                            style="width: 3rem; height: 3rem"
                            fit="contain"
                            :preview-src-list="[scope.row.bookfront1]"
                            preview-teleported
                        />
                    </template>
                </el-table-column>
                <el-table-column
                    prop="bookfront2"
                    label="书本封面背面"
                    width="100"
                >
                    <template #default="scope">
                        <el-image
                            v-if="scope.row.bookfront2"
                            :src="scope.row.bookfront2"
                            style="width: 3rem; height: 3rem"
                            fit="contain"
                            :preview-src-list="[scope.row.bookfront2]"
                            preview-teleported
                        />
                    </template>
                </el-table-column>
                <el-table-column
                    prop="bookPage1"
                    label="书本内容页正面背景图"
                    width="100"
                >
                    <template #default="scope">
                        <el-image
                            v-if="scope.row.bookPage1"
                            :src="scope.row.bookPage1"
                            style="width: 3rem; height: 3rem"
                            fit="contain"
                            :preview-src-list="[scope.row.bookPage1]"
                            preview-teleported
                        />
                    </template>
                </el-table-column>
                <el-table-column
                    prop="bookPage2"
                    label="书本内容页背面背景图"
                    width="100"
                >
                    <template #default="scope">
                        <el-image
                            v-if="scope.row.bookPage2"
                            :src="scope.row.bookPage2"
                            style="width: 3rem; height: 3rem"
                            fit="contain"
                            :preview-src-list="[scope.row.bookPage2]"
                            preview-teleported
                        />
                    </template>
                </el-table-column>
                <el-table-column prop="bookBack" label="书本封底" width="100">
                    <template #default="scope">
                        <el-image
                            v-if="scope.row.bookBack"
                            :src="scope.row.bookBack"
                            style="width: 3rem; height: 3rem"
                            fit="contain"
                            :preview-src-list="[scope.row.bookBack]"
                            preview-teleported
                        />
                    </template>
                </el-table-column>
                <!-- 审批状态和说明 -->
                <el-table-column prop="status" label="审批状态" width="120">
                    <template #default="scope">
                        <el-tag
                            :type="
                                scope.row.status === '已通过'
                                    ? 'success'
                                    : scope.row.status === '未通过'
                                    ? 'danger'
                                    : 'info'
                            "
                        >
                            {{ scope.row.status || "待审批" }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="remark" label="审批说明" width="180" />
                <!-- 编辑操作 -->
                <el-table-column label="操作" width="120">
                    <template #default="scope">
                        <el-button
                            size="small"
                            @click="openEdit(scope.row)"
                            round
                            >编辑</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div style="text-align: center; margin: 24px 0">
                <el-pagination
                    background
                    layout="prev, pager, next"
                    :page-size="pageSize"
                    :total="books.length"
                    v-model:current-page="currentPage"
                />
            </div>
        </el-card>
        <!-- 编辑对话框，布局与主表单一致 -->
        <el-dialog
            v-model="showEditDialog"
            title="编辑书本申请"
            width="1100px"
            center
        >
            <el-form :model="editForm" label-width="140px">
                <el-row :gutter="40">
                    <el-col :span="12">
                        <el-form-item label="角色名称">
                            <el-input
                                v-model="editForm.name"
                                :readonly="true"
                                disabled
                            />
                        </el-form-item>
                        <el-form-item label="简介">
                            <el-input
                                v-model="editForm.desc"
                                type="textarea"
                                rows="4"
                            />
                        </el-form-item>
                        <el-form-item label="是否显示头像">
                            <el-switch v-model="editForm.isAvatar" />
                        </el-form-item>
                        <el-form-item label="头像链接">
                            <el-input v-model="editForm.avatar" />
                            <el-image
                                v-if="editForm.avatar"
                                :src="editForm.avatar"
                                style="
                                    width: 4rem;
                                    height: 6rem;
                                    margin-top: 8px;
                                "
                                fit="contain"
                                :preview-src-list="[editForm.avatar]"
                                preview-teleported
                            />
                        </el-form-item>
                        <el-form-item label="书本封面正面">
                            <el-input v-model="editForm.bookfront1" />
                            <el-image
                                v-if="editForm.bookfront1"
                                :src="editForm.bookfront1"
                                style="
                                    width: 4rem;
                                    height: 6rem;
                                    margin-top: 8px;
                                "
                                fit="contain"
                                :preview-src-list="[editForm.bookfront1]"
                                preview-teleported
                            />
                        </el-form-item>
                        <el-form-item label="书本封面背面">
                            <el-input v-model="editForm.bookfront2" />
                            <el-image
                                v-if="editForm.bookfront2"
                                :src="editForm.bookfront2"
                                style="
                                    width: 4rem;
                                    height: 6rem;
                                    margin-top: 8px;
                                "
                                fit="contain"
                                :preview-src-list="[editForm.bookfront2]"
                                preview-teleported
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="内容页正面背景图">
                            <el-input v-model="editForm.bookPage1" />
                            <el-image
                                v-if="editForm.bookPage1"
                                :src="editForm.bookPage1"
                                style="
                                    width: 4rem;
                                    height: 6rem;
                                    margin-top: 8px;
                                "
                                fit="contain"
                                :preview-src-list="[editForm.bookPage1]"
                                preview-teleported
                            />
                        </el-form-item>
                        <el-form-item label="内容页背面背景图">
                            <el-input v-model="editForm.bookPage2" />
                            <el-image
                                v-if="editForm.bookPage2"
                                :src="editForm.bookPage2"
                                style="
                                    width: 4rem;
                                    height: 6rem;
                                    margin-top: 8px;
                                "
                                fit="contain"
                                :preview-src-list="[editForm.bookPage2]"
                                preview-teleported
                            />
                        </el-form-item>
                        <el-form-item label="书本封底">
                            <el-input v-model="editForm.bookBack" />
                            <el-image
                                v-if="editForm.bookBack"
                                :src="editForm.bookBack"
                                style="
                                    width: 4rem;
                                    height: 6rem;
                                    margin-top: 8px;
                                "
                                fit="contain"
                                :preview-src-list="[editForm.bookBack]"
                                preview-teleported
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 编辑对话框 essay部分，布局同主表单 -->
                <el-form-item label="书本内容" class="essay-form-item">
                    <div
                        v-for="(page, pageIdx) in editForm.essay"
                        :key="pageIdx"
                        class="essay-page-block"
                    >
                        <el-divider>第{{ pageIdx + 1 }}组页</el-divider>
                        <el-row :gutter="24">
                            <el-col :span="12">
                                <el-form-item label="页码">
                                    <el-input
                                        v-model="page.PagesNumeStr"
                                        style="width: 400px"
                                        readonly
                                        placeholder="自动生成"
                                        @change="
                                            (val) =>
                                                handleEditPagesNumeChange(
                                                    page,
                                                    val
                                                )
                                        "
                                    />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="24">
                            <el-col :span="12">
                                <div class="essay-content-title">正面内容</div>
                                <div
                                    v-for="(item, idx) in page.frontContent"
                                    :key="idx"
                                    class="essay-content-row"
                                >
                                    <el-select
                                        v-model="item.type"
                                        placeholder="类型"
                                        style="width: 180px"
                                    >
                                        <el-option label="文本" value="text" />
                                        <el-option label="图片" value="img" />
                                        <el-option label="图片2" value="img2" />
                                        <el-option label="图片3" value="img3" />
                                    </el-select>
                                    <template v-if="item.type === 'text'">
                                        <el-input
                                            v-model="item.text"
                                            type="textarea"
                                            placeholder="文本内容"
                                            style="width: 400px"
                                        />
                                    </template>
                                    <template v-else>
                                        <el-input
                                            v-model="item.Image"
                                            placeholder="图片链接"
                                            style="width: 400px"
                                        />
                                        <el-image
                                            v-if="item.Image"
                                            :src="item.Image"
                                            style="
                                                width: 4rem;
                                                height: 6rem;
                                                margin-top: 8px;
                                            "
                                            fit="contain"
                                            :preview-src-list="[item.Image]"
                                            preview-teleported
                                        />
                                    </template>
                                    <el-button
                                        icon="el-icon-delete"
                                        type="danger"
                                        size="small"
                                        @click="
                                            removeEditEssayContent(
                                                page.frontContent,
                                                idx
                                            )
                                        "
                                        circle
                                    />
                                </div>
                                <el-button
                                    size="small"
                                    type="primary"
                                    @click="
                                        addEditEssayContent(page.frontContent)
                                    "
                                    :disabled="
                                        isEditEssayContentDisabled(
                                            page.frontContent
                                        )
                                    "
                                    style="margin-top: 8px"
                                    >添加内容</el-button
                                >
                            </el-col>
                            <el-col :span="12">
                                <div class="essay-content-title">背面内容</div>
                                <div
                                    v-for="(item, idx) in page.backContent"
                                    :key="idx"
                                    class="essay-content-row"
                                >
                                    <el-select
                                        v-model="item.type"
                                        placeholder="类型"
                                        style="width: 180px"
                                    >
                                        <el-option label="文本" value="text" />
                                        <el-option label="图片" value="img" />
                                        <el-option label="图片2" value="img2" />
                                        <el-option label="图片3" value="img3" />
                                    </el-select>
                                    <template v-if="item.type === 'text'">
                                        <el-input
                                            v-model="item.text"
                                            placeholder="文本内容"
                                            style="width: 400px"
                                        />
                                    </template>
                                    <template v-else>
                                        <el-input
                                            v-model="item.Image"
                                            placeholder="图片链接"
                                            style="width: 400px"
                                        />
                                        <el-image
                                            v-if="item.Image"
                                            :src="item.Image"
                                            style="
                                                width: 4rem;
                                                height: 6rem;
                                                margin-top: 8px;
                                            "
                                            fit="contain"
                                            :preview-src-list="[item.Image]"
                                            preview-teleported
                                        />
                                    </template>
                                    <el-button
                                        icon="el-icon-delete"
                                        type="danger"
                                        size="small"
                                        @click="
                                            removeEditEssayContent(
                                                page.backContent,
                                                idx
                                            )
                                        "
                                        circle
                                    />
                                </div>
                                <el-button
                                    size="small"
                                    type="primary"
                                    @click="
                                        addEditEssayContent(page.backContent)
                                    "
                                    :disabled="
                                        isEditEssayContentDisabled(
                                            page.backContent
                                        )
                                    "
                                    style="margin-top: 8px"
                                    >添加内容</el-button
                                >
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="24">
                                <el-button
                                    size="small"
                                    type="danger"
                                    @click="removeEditEssayPage(pageIdx)"
                                    style="margin-top: 12px"
                                    >删除本组页</el-button
                                >
                            </el-col>
                        </el-row>
                    </div>
                    <el-button
                        size="large"
                        type="success"
                        @click="addEditEssayPage"
                        style="margin-top: 18px"
                        >添加页组</el-button
                    >
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="showEditDialog = false">取消</el-button>
                <el-button
                    type="primary"
                    @click="handleEditSave"
                    :loading="editLoading"
                    >保存</el-button
                >
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
// ====== 导入依赖 ======
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import {
    getUserById, // 获取用户信息（用于自动填充姓名）
    createBookApproval, // 新增书本申请接口
    getUserBookApprovals, // 获取当前用户所有书本申请
    updateBookApproval, // 更新书本申请
} from "./api";

// ====== 基础数据 ======
// 当前登录用户id
const userId = sessionStorage.getItem("user_id");
// 当前登录用户姓名
const userName = ref("");
// 书本申请列表
const books = ref([]);
// 当前分页页码
const currentPage = ref(1);
// 每页显示数量
const pageSize = 5;
// 提交按钮loading状态
const loading = ref(false);

// ====== 主表单数据 ======
const form = reactive({
    userId, // 当前用户id
    name: "", // 角色名称（自动填充）
    desc: "", // 简介
    isAvatar: false, // 是否显示头像
    avatar: "", // 头像链接
    essay: [], // 书本内容页组
    bookfront1: "", // 书本封面正面
    bookfront2: "", // 书本封面背面
    bookPage1: "", // 内容页正面背景图
    bookPage2: "", // 内容页背面背景图
    bookBack: "", // 书本封底
    remark: "", // 审批说明
});

// ====== essay动态表单相关（主表单） ======
// 添加页组，自动生成连续页码
function addEssayPage() {
    let maxPage = 0;
    form.essay.forEach((page) => {
        if (Array.isArray(page.PagesNume) && page.PagesNume.length > 0) {
            const localMax = Math.max(...page.PagesNume);
            if (localMax > maxPage) maxPage = localMax;
        }
    });
    const newPages = [maxPage + 1, maxPage + 2];
    form.essay.push({
        PagesNume: newPages,
        PagesNumeStr: newPages.join(","),
        frontContent: [],
        backContent: [],
    });
}
// 删除页组
function removeEssayPage(idx) {
    form.essay.splice(idx, 1);
}
// 添加内容项（默认文本）
function addEssayContent(arr) {
    arr.push({ type: "text", text: "" });
}
// 删除内容项
function removeEssayContent(arr, idx) {
    arr.splice(idx, 1);
}
// 页码输入变化时同步数组
function handlePagesNumeChange(page, val) {
    page.PagesNume = val
        .split(",")
        .map((v) => parseInt(v.trim()))
        .filter((v) => !isNaN(v));
    page.PagesNumeStr = val;
}
// 内容添加按钮禁用逻辑
function isEssayContentDisabled(arr) {
    if (arr.length === 0) return false;
    if (["img2", "img3"].includes(arr[0].type)) return arr.length >= 1;
    return arr.length >= 3;
}

// ====== 编辑对话框 essay 操作（独立于主表单） ======
function addEditEssayPage() {
    let maxPage = 0;
    (editForm.essay || []).forEach((page) => {
        if (Array.isArray(page.PagesNume) && page.PagesNume.length > 0) {
            const localMax = Math.max(...page.PagesNume);
            if (localMax > maxPage) maxPage = localMax;
        }
    });
    const newPages = [maxPage + 1, maxPage + 2];
    if (!editForm.essay) editForm.essay = [];
    editForm.essay.push({
        PagesNume: newPages,
        PagesNumeStr: newPages.join(","),
        frontContent: [],
        backContent: [],
    });
}
function removeEditEssayPage(idx) {
    editForm.essay.splice(idx, 1);
}
function addEditEssayContent(arr) {
    arr.push({ type: "text", text: "" });
}
function removeEditEssayContent(arr, idx) {
    arr.splice(idx, 1);
}
function handleEditPagesNumeChange(page, val) {
    page.PagesNume = val
        .split(",")
        .map((v) => parseInt(v.trim()))
        .filter((v) => !isNaN(v));
    page.PagesNumeStr = val;
}
function isEditEssayContentDisabled(arr) {
    if (arr.length === 0) return false;
    if (["img2", "img3"].includes(arr[0].type)) return arr.length >= 1;
    return arr.length >= 3;
}

// ====== 生命周期钩子 ======
// 页面加载时自动填充姓名、初始化essay页码字符串、获取申请记录
onMounted(() => {
    // essay页码字符串初始化
    form.essay.forEach((page) => {
        page.PagesNumeStr = (page.PagesNume || []).join(",");
    });
    // 自动填充当前登录人姓名
    if (userId) {
        getUserById(userId).then((user) => {
            userName.value = user.name || "";
            form.name = userName.value;
        });
    }
    fetchBooks();
});

// ====== 编辑对话框相关 ======
const showEditDialog = ref(false); // 编辑弹窗显示状态
const editForm = reactive({
    userId,
    name: "",
    desc: "",
    isAvatar: false,
    avatar: "",
    bookfront1: "",
    bookfront2: "",
    bookPage1: "",
    bookPage2: "",
    bookBack: "",
    status: "待审批",
});
const editLoading = ref(false);

// ====== 书本申请分页 ======
const pagedBooks = computed(() => {
    const start = (currentPage.value - 1) * pageSize;
    return books.value.slice(start, start + pageSize);
});

// ====== 获取书本申请记录 ======
function fetchBooks() {
    if (userId) {
        getUserBookApprovals(userId).then((res) => {
            books.value = res;
            currentPage.value = 1;
        });
    }
}

// ====== 提交申请 ======
function handleSubmit() {
    // 校验所有必填项
    if (
        !form.name ||
        !form.bookfront1 ||
        !form.bookfront2 ||
        !form.bookPage1 ||
        !form.bookPage2 ||
        !form.bookBack
    ) {
        ElMessage.warning("请填写完整信息");
        return;
    }
    loading.value = true;
    // essay去掉PagesNumeStr，仅提交必要字段
    const essay = form.essay.map((page) => ({
        PagesNume: page.PagesNume,
        frontContent: page.frontContent,
        backContent: page.backContent,
    }));
    createBookApproval({
        userId,
        ...form,
        essay,
    })
        .then((res) => {
            ElMessage.success(res.message);
            fetchBooks();
            // 重置表单
            Object.assign(form, {
                userId,
                name: userName.value,
                desc: "",
                isAvatar: false,
                avatar: "",
                essay: [],
                bookfront1: "",
                bookfront2: "",
                bookPage1: "",
                bookPage2: "",
                bookBack: "",
            });
        })
        .catch((err) => {
            ElMessage.error(err.response?.data?.error || "提交失败");
        })
        .finally(() => {
            loading.value = false;
        });
}

// ====== 编辑弹窗相关 ======
// 打开编辑弹窗并填充数据
function openEdit(row) {
    Object.assign(editForm, row);
    // 补全每个页组的 PagesNumeStr
    if (editForm.essay && Array.isArray(editForm.essay)) {
        editForm.essay.forEach((page) => {
            page.PagesNumeStr = (page.PagesNume || []).join(",");
        });
    }
    showEditDialog.value = true;
}
// 保存编辑内容
function handleEditSave() {
    if (!editForm.name) {
        ElMessage.warning("名称不能为空");
        return;
    }
    editLoading.value = true;
    editForm.status = "待审批";
    updateBookApproval(editForm._id, {
        operatorId: userId,
        ...editForm,
    })
        .then((res) => {
            ElMessage.success(res.message);
            showEditDialog.value = false;
            fetchBooks();
        })
        .catch((err) => {
            ElMessage.error(err.response?.data?.error || "更新失败");
        })
        .finally(() => {
            editLoading.value = false;
        });
}
</script>

<style scoped>
/* 页面整体居中 */
.book-page {
    display: flex;
    justify-content: center;
}
/* 卡片样式 */
.book-card {
    width: 100%;
    border-radius: 24px;
    box-shadow: 0 8px 32px 0 rgba(60, 60, 120, 0.12);
    padding: 48px 64px 64px 64px;
    background: #fff;
}
/* 标题样式 */
.book-title {
    text-align: center;
    font-size: 2.2rem;
    font-weight: bold;
    color: #409eff;
    margin-bottom: 32px;
    letter-spacing: 2px;
}
/* 表单底部间距 */
.book-form {
    margin-bottom: 32px;
}
/* essay表单项宽度 */
.essay-form-item {
    width: 100%;
}
/* essay页组块样式 */
.essay-page-block {
    border: 1px solid #e4e7ed;
    border-radius: 12px;
    padding: 32px;
    margin-bottom: 32px;
    background: #fafdff;
}
/* essay内容标题 */
.essay-content-title {
    font-size: 1.15rem;
    font-weight: bold;
    margin-bottom: 12px;
    color: #409eff;
}
/* essay内容项布局 */
.essay-content-row {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 12px;
}
/* 申请记录表格样式 */
.book-table {
    margin-top: 32px;
}
</style>